package com.jh.user.controller;

import cn.jh.common.core.json.JsonKt;
import cn.jh.common.exception.ServiceException;
import cn.jh.common.pay.jdpush.PayBarException;
import cn.jh.common.pay.security.AESUtil;
import cn.jh.common.pay.utils.Commons;
import com.jh.user.pojo.enums.ChannelMerType;
import com.jh.user.repository.ChannelRateRepository;
import cn.jh.common.utils.*;
import com.jh.user.business.*;
import com.jh.user.pojo.*;
import com.jh.user.pojo.enums.CardType;
import com.jh.user.pojo.enums.PayTypeQu;
import com.jh.user.pojo.freeQuick.BindCardNotify;
import com.jh.user.pojo.freeQuick.PassageWayRegister;
import com.jh.user.pojo.freeQuick.PassagewayBankInfo;
import com.jh.user.repository.UserAccountRepository;
import com.jh.user.repository.freeQuick.PassageWayRegisterRepository;
import com.jh.user.service.freeQuick.FreeQuickService;
import net.sf.json.JSONArray;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.math.BigDecimal;
import java.util.*;

import static cn.jh.common.utils.BaseApi.JSON_UTF8;
import static org.springframework.util.StringUtils.hasText;
import static org.springframework.web.bind.annotation.RequestMethod.POST;

/**
 * 畅捷通道
 *
 * @author chengyingli
 * @date 2018年08月24
 */
@Controller
@EnableAutoConfiguration
public class FreeQuickBindCardController {

    private Logger log = LoggerFactory.getLogger(FreeQuickBindCardController.class);

    private final FreeQuickService freeQuickService;
    private final UserBankInfoBusiness userBankInfoBusiness;
    private final ChannelRateBusiness channelRateBusiness;
    private final ChannelRateRepository channelRateRepository;
    private final UserLoginRegisterBusiness userLoginRegisterBusiness;
    private final UserRoleResourceBusiness userRoleResourceBusiness;
    private final ShopRegisterBussiness shopRegisterBussiness;
    private final PassageWayRegisterRepository passageWayRegisterRepository;
    private final UserAccountRepository userAccountRepository;

    @Autowired
    public FreeQuickBindCardController(FreeQuickService freeQuickService,
                                       UserBankInfoBusiness userBankInfoBusiness,
                                       ChannelRateBusiness channelRateBusiness,
                                       UserLoginRegisterBusiness userLoginRegisterBusiness,
                                       UserRoleResourceBusiness userRoleResourceBusiness,
                                       ShopRegisterBussiness shopRegisterBussiness,
                                       PassageWayRegisterRepository passageWayRegisterRepository,
                                       UserAccountRepository userAccountRepository,
                                       ChannelRateRepository channelRateRepository) {
        this.freeQuickService = freeQuickService;
        this.userBankInfoBusiness = userBankInfoBusiness;
        this.channelRateBusiness = channelRateBusiness;
        this.userLoginRegisterBusiness = userLoginRegisterBusiness;
        this.userRoleResourceBusiness = userRoleResourceBusiness;
        this.shopRegisterBussiness = shopRegisterBussiness;
        this.passageWayRegisterRepository = passageWayRegisterRepository;
        this.userAccountRepository = userAccountRepository;
        this.channelRateRepository = channelRateRepository;
    }

    /**
     * 通道注册
     *
     * @param entity
     * @return
     */
    @RequestMapping(method = RequestMethod.POST, value = ("/v1.0/user/app/query/RegisterMerchant"), produces = JSON_UTF8)
    public @ResponseBody
    Object appreimbursement(PassageWayRegister entity) {
        try {
            return appreimbursements(entity);
        } catch (ServiceException e) {
            e.printStackTrace();
            return CommonsUtil.returnError(e.getMessage());
        } catch (Exception e) {
            log.info("FreeQuickController.registerMerchant,智能还款userId=====" + entity.getUserId() + "，异常==========" + e.getMessage());
            return CommonsUtil.returnError(Constss.ERROR_CODE, "智能还款失败！" + e.getMessage());
        }
    }

    /**
     * 调用注册接口
     *
     * @param entity
     * @return
     * @throws Exception
     */
    public Map appreimbursements(PassageWayRegister entity) throws ServiceException {
        Map pram = new HashMap();
        PassageWayRegister passageWayRegister = new PassageWayRegister();
        //查询通道是否注册
        List<PassageWayRegister> result = passageWayRegisterRepository.findByUserId(entity.getUserId());
        if (result.size() > 0 ) {
            int count = 0;
            for (PassageWayRegister register : result) {
                if (StringUtils.isNotBlank(entity.getChannelProductCode())
                        && entity.getChannelProductCode().equals(register.getChannelProductCode())) {
                    count++;
                }
                pram.put("merchantNo",register.getRequestNo());
                passageWayRegister = register;
            }
            if (count < 1) {
                passageWayRegister.setUserId(entity.getUserId());
                passageWayRegister.setChannelProductCode(entity.getChannelProductCode());
                //开通
                pram = freeQuickService.registerProduct(passageWayRegister, Integer.valueOf(entity.getUserId()));
                pram.put("merchantNo",passageWayRegister.getMerchantNo());
            }
        } else {
            //用户没有选择渠道默认开通畅捷新无卡101
            if (StringUtils.isBlank(entity.getChannelProductCode())) {
                entity.setChannelProductCode("2");
            }
            //注册
            pram = freeQuickService.registerMerchant(entity, entity.getUserId());

        }

        return CommonsUtil.returnSuccess("接口调用成功",pram);
    }

    /**
     * 畅捷提交短信验证
     * @param smsCode
     * @return
     */
    @RequestMapping(method = RequestMethod.POST, value = ("/v1.0/user/bind/bindCardConfirm/{token}"), produces = JSON_UTF8)
    public @ResponseBody
    Object bindCardConfirm(@PathVariable("token") String token,String smsCode,String bankCode) {
        long userId = 0;
        try {
            userId = TokenUtil.getUserId(token);
            Map map = freeQuickService.bindCardConfirm(smsCode, userId,bankCode);
            String bizMsg = (String) map.getOrDefault("bizMsg", "0");
            String bizCode = (String) map.getOrDefault("bizCode", "0");
            String code = (String) map.getOrDefault("code", "0");
            if (code.equals(CommonConstants.FREE_SUCCESS)) {
                if (bizCode.equals("1")) {
                    return CommonsUtil.returnSuccess("短信验证成功");
                } else {
                    return CommonsUtil.returnError(bizCode, bizMsg);
                }
            } else {
                return CommonsUtil.returnError("短信验证失败，请重新输入！");
            }
        } catch (ServiceException e) {
            e.printStackTrace();
            return CommonsUtil.returnError(e.getMessage());
        } catch (Exception e) {
            log.info("FreeQuickController.bindCardConfirm,提交短信验证userId=====" + userId + "异常==========" + e.getMessage());
            e.printStackTrace();
            return CommonsUtil.returnError(Constss.ERROR_CODE, "提交短信验证失败！" + e.getMessage());
        }

    }

    /**
     * 短信验证绑定银行卡回调方法
     *
     * @param request
     * @return
     */
    @RequestMapping(method = RequestMethod.POST, value = ("/v1.0/user/callback/bindCard"), produces = JSON_UTF8)
    public String bindCardCallback(HttpServletRequest request) {
        String data = request.getParameter("data");
        String content = !hasText(data) ? null : AESUtil.decrypt(data, Commons.AGENT_KEY);
        if (!hasText(content)) {
            return "FAILURE";
        }
        try {
            BindCardNotify notify = JsonKt.readValue(content, BindCardNotify.class);
            notify.setContent(content);
            freeQuickService.processBindCardNotify(notify);
        } catch (PayBarException e) {
            e.printStackTrace();
            return "FAILURE";
        } catch (Exception ex) {
            log.error(ex.getMessage());
            return "FAILURE";
        }
        return "SUCCESS";
    }


    /**
     * 商户开通产品
     */
    @RequestMapping(method = RequestMethod.POST, value = ("/v1.0/user/register/product/{token}"), produces = JSON_UTF8)
    public @ResponseBody
    Object registerProduct(@PathVariable("token") String token, PassageWayRegister entity) {
        long userId = 0;
        try {
            userId = TokenUtil.getUserId(token);
            Map map = freeQuickService.registerProduct(entity, userId);
            String bizCode = (String) map.getOrDefault("bizCode", "0");
            String binkMsg = (String) map.getOrDefault("binkMsg", "0");
            if (bizCode.equals("1")) {
                return CommonsUtil.returnSuccess("产品开通成功！");
            } else {
                return CommonsUtil.returnError(bizCode, binkMsg);
            }
        } catch (Exception e) {
            log.error("FreeQuickController.registerProduct,产品开通" + userId + ",异常======" + e.getMessage());
            e.printStackTrace();
            return CommonsUtil.returnError("产品开通失败！" + e.getMessage());
        }
    }

    /**
     * 查询银行卡接口
     * @param cardNo
     * @return
     */
    @RequestMapping(method = RequestMethod.POST, value = ("/v1.0/user/register/bankInfo"), produces = JSON_UTF8)
    public @ResponseBody
    Object bankInfoByCardNo(String cardNo, long userId, String channelType) {
        Map map = new HashMap();
        try {
            PassageWayRegister register = new PassageWayRegister();
            register.setUserId(userId + "");
            register.setChannelProductCode(channelType);
            register.setSettleBankAccountNo(cardNo);
            //判断通道是否注册
            Map pram = appreimbursements(register);
            Map maps = (Map) pram.getOrDefault("result", "0");
            String respCode = (String) pram.getOrDefault("resp_code", "0");
            String merchantNo = (String) maps.getOrDefault("merchantNo", "0");
            String bizCode = "";
            String bizMsg = "";
            if (!respCode.equals(CommonConstants.SUCCESS)) {
                if (maps != null) {
                    bizCode = (String) maps.getOrDefault("bizCode", "0");
                    bizMsg = (String) maps.getOrDefault("bizMsg", "0");
                    maps.put("bizCode", bizCode);
                    maps.put("bizMsg", bizMsg);
                }
                return CommonsUtil.returnError(bizCode, bizMsg);
            }
            Map prams = new HashMap();

            //判断银行卡通道是否绑定
            PassagewayBankInfo infos = freeQuickService.queryBankInfoAndChannelProductCode(cardNo,channelType);
            //查询消费银行卡信息
            UserBankInfo userBankInfo = userBankInfoBusiness.findUserBankInfoByCardNo(cardNo);
            if(infos == null) {
                //绑定银行卡
                prams = freeQuickService.bindCard(userBankInfo, merchantNo, Integer.valueOf(channelType),0);
            }else{
                if(!infos.getBindStatus().equals("1")){
                    //绑定银行卡
                    prams = freeQuickService.bindCard(userBankInfo, merchantNo, Integer.valueOf(channelType),infos.getId());
                }
            }
            if(!prams.isEmpty() && prams.size() > 0){
                String binkCode = (String) prams.getOrDefault("binkCode", "0");
                String bindStatus = (String) prams.getOrDefault("bindStatus", "0");
                bizMsg = (String) prams.getOrDefault("bizMsg", "0");

                if(!binkCode.equals("1")){
                    boolean fle = CommonsUtil.verifyError(binkCode);
                    if(!fle){
                        map.put("cardType","1");
                        map.put(CommonConstants.RESP_CODE,binkCode);
                        map.put(CommonConstants.RESP_MESSAGE,bindStatus);
                        map.put("cardNo",cardNo);
                        return map;
                    }
                }
                if(org.apache.commons.lang.StringUtils.isNotBlank(bindStatus)){
                    if(!CommonConstants.BASE_SUCCESS.equalsIgnoreCase(bindStatus) && !bindStatus.equals("0")){
                        if (bindStatus.equals(CommonConstants.PENDING)) {
                            map.put("cardType", "1");
                            map.put(CommonConstants.RESP_CODE, binkCode);
                            map.put(CommonConstants.RESP_MESSAGE, bindStatus);
                            map.put("cardNo", cardNo);
                            return map;
                        } else {
                            return CommonsUtil.returnError(binkCode, bizMsg);
                        }

                    }


                }
            }
            //查询结算卡
            UserBankInfo bankInfo = userBankInfoBusiness.findUserId(userId);
            if(bankInfo == null){
                return CommonsUtil.returnError(CommonConstants.ERROR_BINK_ERROR,"您未绑定结算卡，请绑定结算卡！");
            }

            //查询费率
            ChannelRate  channelRate = channelRateRepository.findChannelRate(userId,"1" ,Integer.valueOf(channelType),Short.parseShort("1"));

            map.put("merchantNo", merchantNo);

            map.put("userBankInfo", userBankInfo);
            map.put("channelRate", channelRate);
            return CommonsUtil.returnSuccess("查询成功", map);
        } catch (ServiceException e) {
            e.printStackTrace();
            return CommonsUtil.returnError(e.getMessage());
        } catch (Exception e) {
            log.error("查询银行卡接口异常======" + e.getMessage());
            e.printStackTrace();
            return CommonsUtil.returnError("查询银行卡接口失败！");
        }

    }

    /**
     * 查询用户信息
     */
    @RequestMapping(method = RequestMethod.POST, value = "/v1.0/user/freeQtuick/user")
    public @ResponseBody
    Object findByUserId(@RequestParam(value = "userId") long userId, String channelTag, long payType) {
        Map map = new HashMap<>();
        try {
            User user = userLoginRegisterBusiness.queryUserById(userId);
            List<Channel> list = channelRateBusiness.findAllChannel(userId, payType, 0, "", "");

            Collections.sort(list, (arg0, arg1) -> arg1.getChannelNo().compareTo(arg0.getChannelNo()));
            HashSet<Channel> h = new HashSet<>(list);
            list.clear();
            list.addAll(h);
            if (user != null) {
                map.put("brandId", user.getBrandId());
                map.put("phone", user.getPhone());
                map.put("brandName", user.getBrandname());
            }
            if (!list.isEmpty() && list.size() > 0) {
                for (Channel chann : list) {
                    //交易类型1交易，2提现
                    if (chann.getPayType().equals("1")) {
                        map.put("payId", chann.getChannelNo());
                        map.put("payChannelTag", chann.getChannelTag());
                        map.put("payChannelType", chann.getChannelType());
                        map.put("payAutoclearing", chann.getAutoclearing());
                        map.put("payRate", chann.getRate());
                        map.put("extraFee", chann.getRate());

                    } else {
                        map.put("id", chann.getChannelNo());
                        map.put("rate", chann.getRate());
                        map.put("extraFee", chann.getExtraFee());
                        map.put("channelTag", chann.getChannelTag());
                        map.put("channelType", chann.getChannelType());
                        map.put("autoclearing", chann.getAutoclearing());
                        map.put("costRate", chann.getCostRate());
                        map.put("extraFee", chann.getRate());

                    }
                }
            }
            return CommonsUtil.returnSuccess("查询成功", map);
        } catch (Exception e) {
            log.error("查询用户信息和渠道信息异常======" + e.getMessage());
            e.printStackTrace();
            return CommonsUtil.returnError("查询用户信息和渠道信息失败！" + e.getMessage());
        }

    }

    /**
     * 查询用户信息推荐人费率和银行卡信息
     *
     * @param userId
     * @param cardNo
     * @return
     */
    @RequestMapping(method = RequestMethod.POST, value = "/v1.0/user/freeQtuick/gradeRate")
    public @ResponseBody Object queryGradeRate(@RequestParam(value = "userId") long userId,String cardNo,String channelId,String payType) {
        Map map = new HashMap<>();
        try {

            String brandUserId = "";
            String preUserId = "";
            BigDecimal brandRate = BigDecimal.ZERO;
            BigDecimal gradeRate = BigDecimal.ZERO;
            User user = userLoginRegisterBusiness.queryUserById(userId);
            Map pram = userLoginRegisterBusiness.queryGrade(userId);
            if (!pram.isEmpty()) {
                String grade = (String) pram.getOrDefault("grade", "0");
                preUserId = (String) pram.getOrDefault("preUserId", "0");
                BrandRate brand = channelRateBusiness.queryBrandRate(channelId, payType, grade);
                gradeRate = brand.getGradeRate();
            }


            Map param = userLoginRegisterBusiness.queryBandId(user.getBrandId() + "");
            if (!param.isEmpty()) {
                brandUserId = (String) param.getOrDefault("userId", "0");
                BrandRate brand = channelRateBusiness.queryBrandRate(channelId, payType, "6");
                brandRate = brand.getBrandRate();
            }

            User user1 = userLoginRegisterBusiness.getPreUserId(userId);
            if (null == user1) {
                return CommonsUtil.returnError("无用户信息！");
            }
            long preUserIdd = user.getPreUserId();
            String grade = user.getGrade();
            BrandRate brand = channelRateBusiness.queryBrandRate(channelId, payType, grade);
            gradeRate = brand.getGradeRate();
            if (null == gradeRate) {
                gradeRate = BigDecimal.ZERO;
            }
            brandRate = brand.getBrandRate();
            if (null == brandRate) {
                brandRate = BigDecimal.ZERO;
            }
            long brandUserIdd = userLoginRegisterBusiness.getBrand(user.getBrandId());

            map.put("brandRate", brandRate);
            map.put("brandUserId", brandUserId);
            map.put("gradeRate", gradeRate);
            map.put("preUserId", preUserId);

            map.put("preUserId", String.valueOf(preUserIdd));
            map.put("brandUserId", String.valueOf(brandUserIdd));


            UserBankInfo info = userBankInfoBusiness.findCreditCardManagerConfig(cardNo);
            map.put("info", info);
            return CommonsUtil.returnSuccess("查询成功", map);
        } catch (Exception e) {
            log.error("查询用户信息和渠道信息异常======" + e.getMessage());
            return CommonsUtil.returnError("查询用户信息和渠道信息失败！" + e.getMessage());
        }

    }

    /**
     * 绑卡回调
     */
    @RequestMapping(value = {"/callback/bind_card", "/callback/consume"}, method = POST, produces = "text/plain")
    public String bindCard(HttpServletRequest request) {
        String requestURI = request.getRequestURI();
        boolean isBindCard = requestURI.endsWith("/bind_card");
        // 回调数据['bizType':'PAY', 'data':'xxxxxxxxxxxxxx']
        String data = request.getParameter("data");
        String content = !hasText(data) ? null : AESUtil.decrypt(data, CommonConstants.AGENT_KEY);
        if (!hasText(content)) {
            return "FAILURE";
        }
        try {
            BindCardNotify notify = JsonKt.readValue(content, BindCardNotify.class);
            // 返回数据：{"requestNo":"1532499761828","bindStatus":"SUCCESS","merchantNo":"1318072510059614"}
            freeQuickService.processPayNotify(notify);
        } catch (PayBarException ex) {
            log.error(ex.getMessage());
            return "FAILURE";
        }
        return "SUCCESS";
    }

    /**
     * 查询通道注册信息
     *
     * @param entity
     * @return
     */
    @RequestMapping(method = RequestMethod.POST, value = "/v1.0/user/freeQtuick/merchant")
    public @ResponseBody
    Object queryRegisterMerchant(PassageWayRegister entity) {
        try {
            PassageWayRegister register = freeQuickService.queryRegisterMerchant(entity);
            ChannelRate rate = channelRateBusiness.findAllChannelRate(Integer.valueOf(entity.getUserId()),1,entity.getChannelProductCode());
            Map map = new HashMap();
            map.put("channelRate",rate);
            map.put("register",register);
            return CommonsUtil.returnSuccess("查询通道注册信息成功", map);
        } catch (Exception e) {
            log.error("FreeQuickPayServiceImpl.queryRegisterMerchant,查询通道注册信息=====" + entity.getUserId() + ",异常===" + e.getMessage());
            return CommonsUtil.returnError("查询通道注册信息失败！");
        }
    }

    /**
     * 通道绑卡
     *
     * @param userId
     * @param merchantNo
     * @param channelProductCode
     * @return
     */
    @RequestMapping(method = RequestMethod.POST, value = "/v1.0/user/freeQtuick/bindCard")
    public @ResponseBody Object bindCard(String userId, String merchantNo, int channelProductCode) {
        Map map = new HashMap();
        try {
            UserBankInfo card = userBankInfoBusiness.findUserBankInfoByUseridAndIdDef(Integer.valueOf(userId), "1", "0");
            if (card != null) {
                return CommonsUtil.returnError("绑卡失败,未查出该银行卡信息！");
            }
            return CommonsUtil.returnSuccess("绑卡未发生异常", freeQuickService.bindCard(card, merchantNo, channelProductCode,0));
        } catch (Exception e) {
            log.error("FreeQuickBindCardController.bindCard,通道绑卡异常=====" + e.getMessage());
            e.printStackTrace();
            return CommonsUtil.returnError("绑卡失败！");
        }
    }

    @RequestMapping(method = RequestMethod.POST, value = "/v1.0/user/freeQtuick/modifyMerchantFeeInfo")
    public @ResponseBody Object modifyMerchantFeeInfo(String requestNo,String merchantNo,String channelProductCode,String cardType,String bizType,String feeValue) throws ServiceException{
        Map map = new HashMap();

        try {
            map = freeQuickService.modifyMerchantFeeInfo(requestNo,merchantNo,channelProductCode,cardType,bizType,feeValue);
            return map;
        }catch (Exception e){
            return map;
        }
    }

    /**
     * 查询银行卡
     * @param cardNo
     * @return
     */
    @RequestMapping(method = RequestMethod.POST, value = "/v1.0/user/freeQtuick/queryBankInfo")
    public @ResponseBody Object queryBankInfo(String cardNo){
        try {
            UserBankInfo userBankInfo = userBankInfoBusiness.findUserBankInfoByCardNo(cardNo);
            return CommonsUtil.returnSuccess("",userBankInfo);
        }catch (Exception e){
            log.error("FreeQuickBindCardController.queryBankInfo,查询银行卡异常====="+e.getMessage());
            e.printStackTrace();
            return CommonsUtil.returnError("查询银行卡失败！");
        }

    }

    /**
     * 保存分润信息
     * @param account
     * @return
     */
    @RequestMapping(method = RequestMethod.POST, value = "/v1.0/user/freeQtuick/saveAccount")
    public @ResponseBody Object saveAccount(UserAccount account){
        try{
            UserAccount user = userAccountRepository.getUserAccount(account.getUserId());
            if(user != null){
                BigDecimal rebateBalance = user.getRebateBalance();
                rebateBalance = rebateBalance.add(account.getRebateBalance());
                user.setRebateBalance(rebateBalance);
            }else{
                user = account;
            }
            freeQuickService.saveUserAccount(user);
            return CommonsUtil.returnSuccess("保存分润成功！");
        }catch (Exception e){
            return CommonsUtil.returnError("保存分润失败!");
        }
    }

    /**
     * 分页获取商户通道注册列表信息
     * @param token
     * @param merchantNo 商户注册通道编号
     * @param merchantName 商户名称
     * @param pwrStatus 注册状态：0可用，1不可用
     * @param bindMobile 商户绑定通道手机号码
     * @param page
     * @param size
     * @param direction
     * @param sortProperty
     * @return
     */
    @PostMapping(value = "/v1.0/user/freeQtuick/queryMerchantFeeInfoList/{token}")
    public @ResponseBody Object queryMerchantFeeInfoList(@PathVariable("token") String token,
                                                         @RequestParam(value = "merchantNo", required = false) String merchantNo,
                                                         @RequestParam(value = "merchantName", required = false) String merchantName,
                                                         @RequestParam(value = "pwrStatus", required = false) String pwrStatus,
                                                         @RequestParam(value = "bindMobile", required = false) String bindMobile,
                                                         @RequestParam(value = "page", defaultValue = "0", required = false) int page,
                                                         @RequestParam(value = "size", defaultValue = "20", required = false) int size,
                                                         @RequestParam(value = "order", defaultValue = "DESC", required = false)Sort.Direction direction,
                                                         @RequestParam(value = "sort", defaultValue = "createTime", required = false) String sortProperty) {
        // 1、获取userId
        long userId;
        try {
            userId = TokenUtil.getUserId(token);
        } catch (Exception e) {
            return CommonsUtil.returnError("token无效！");
        }

        // 2、根据userId获取用户角色信息
        try {
            long roleId = getUserRoleId(userId);
            if (roleId != 1) {
                // 1为系统管理员
                return CommonsUtil.returnError("非系统管理员无法查看商户通道注册列表信息！");
            }
        } catch (Exception e) {
            e.printStackTrace();
            return CommonsUtil.returnError("获取用户角色信息失败！");
        }

        try {
            // 3、获取商户信息
            Pageable pageable = new PageRequest(page, size, new Sort(direction, sortProperty));
            Map<String, Object> passageWayRegisterMap = freeQuickService.queryMerchantFeeInfoList(merchantNo, merchantName, pwrStatus, bindMobile, pageable);
            return CommonsUtil.returnSuccess("查询成功！", passageWayRegisterMap);
        } catch (Exception e) {
            return CommonsUtil.returnError("服务器异常，请稍后再试！");
        }
    }

    /**
     * 获取用户角色
     * @param userId id
     * @return
     * @throws Exception
     */
    private long getUserRoleId(long userId) throws ServiceException {
        Map<String, Object> map = userRoleResourceBusiness.queryUserRole(userId);
        Object roleId = map.get("roleId");
        long roleid = 5;
        if (roleId instanceof Long) {
            roleid = Long.parseLong(roleId.toString());
        }
        return roleid;
    }

    /**
     * 查询某商户费率信息：merchantNo为我们显示给用户的商户编号，requestNo为上游通道给我们生成的商户编号，要根据requestNo查询上游商户费率信息
     * @param merchantNo 商户编号
     * @return
     */
    @PostMapping(value = "/v1.0/user/freeQtuick/queryOneForMerchantFeeInfo")
    public @ResponseBody Object queryMerchantFeeInfo(@RequestParam(value = "merchantNo")String merchantNo) {
        try {
            if (StringUtils.isEmpty(merchantNo)) {
                return CommonsUtil.returnError("商户编号为空！");
            }
            return freeQuickService.queryMerchantFeeInfo(merchantNo);
        } catch (ServiceException e) {
            e.printStackTrace();
            return CommonsUtil.returnError(e.getMessage());
        } catch (Exception e) {
            e.printStackTrace();
            return CommonsUtil.returnError("服务器异常，请稍后再试！");
        }
    }

    /**
     * 后台-商户通道注册
     * @param token
     * @param entity:
     *              channelProductCode：通道产品编码
     *              bindMobile 商户手机号码
     *              merchantNo 商户通道编号，即shopRegister中的shopId
     * @return
     */
    @PostMapping(value = "//v1.0/user/freeQtuick/merchantToSignupChannel/{token}")
    public @ResponseBody Object merchantToSignupChannel(@PathVariable("token") String token, PassageWayRegister entity) {
        long userId;
        try {
            userId = TokenUtil.getUserId(token);
        } catch (Exception e) {
            return CommonsUtil.returnError("token无效！");
        }

        // 1、根据userId获取当前系统管理员的角色信息
        try {
            long roleId = getUserRoleId(userId);
            if (roleId != 1) {
                // 1为系统管理员
                return CommonsUtil.returnError("非系统管理员无法对该商户进行通道注册操作！");
            }
        } catch (Exception e) {
            e.printStackTrace();
            return CommonsUtil.returnError("获取系统管理员角色信息失败！");
        }

        // 2、查询通道是否注册
        try {
            String channelProductCode = entity.getChannelProductCode();
            List<PassageWayRegister> result = passageWayRegisterRepository.findByUserId(entity.getUserId());
            if (result.size() > 0) {
                for (PassageWayRegister register : result) {
                    String existChannelProductCode = register.getChannelProductCode();
                    if (StringUtils.isNotEmpty(existChannelProductCode)) {
                        if (channelProductCode.equals(existChannelProductCode)) {
                            return CommonsUtil.returnError("商户已注册该通道！");
                        }
                    }
                }
            }
        } catch (Exception e) {
            log.error("查询该商户的通道信息异常,pram {}" + e.getMessage());
            return CommonsUtil.returnError("查询该商户的通道信息异常，请稍后再试！");
        }

        // 3、根据bindMobile获取商户基本信息
        User user;
        try {
            String bindMobile = entity.getBindMobile();
            if (!bindMobile.matches("^1\\d{10}$")) {
                return CommonsUtil.returnError("商户手机号码输入错误！");
            }
            user = userLoginRegisterBusiness.queryUserByPhone(bindMobile);
            if (null == user) {
                return CommonsUtil.returnError("无该商户信息，请确认信息是否正确！");
            }
            String realnameStatus = user.getRealnameStatus();
            if (!"1".equals(realnameStatus)) {
                return CommonsUtil.returnError("该商户还未通过实名认证，无法注册通道！");
            }
        } catch (Exception e) {
            e.printStackTrace();
            return CommonsUtil.returnError("获取商户基本信息异常，请稍后再试！");
        }

        // 4、根据商户编号查询商户信息是否已经审核通过
        try {
            String merchantNo = entity.getMerchantNo();
            if (StringUtils.isEmpty(merchantNo)) {
                return CommonsUtil.returnError("商户编号为空！");
            }
            ShopRegister shopRegister = shopRegisterBussiness.getByShopId(user.getId(), merchantNo);
            if (null == shopRegister) {
                return CommonsUtil.returnError("该商户无商店信息，请确认信息！");
            }
            Integer status = shopRegister.getStatus();
            if (status != 5) {
                return CommonsUtil.returnError("该商户的商铺信息还未审核通过！");
            }
        } catch (Exception e) {
            e.printStackTrace();
            return CommonsUtil.returnError("根据商户编号查询商户信息异常，请稍后再试！");
        }

        // 5、通道注册
        try {
            Map<String, Object> map = freeQuickService.registerMerchant(entity, String.valueOf(user.getId()));
            return CommonsUtil.returnSuccess("注册通道接口调用成功！", map);
        } catch (ServiceException e) {
            e.printStackTrace();
            return CommonsUtil.returnError(e.getMessage());
        } catch (Exception e) {
            e.printStackTrace();
            return CommonsUtil.returnError("该商户注册通道信息失败，请稍后再试！");
        }
    }


    /**
     * 后台-商户修改结算卡信息接口：代理商通过该接口可修改已绑定的结算卡信息。
     * @param token
     * @param lineNo        联行号
     * @param province      开户省
     * @param city          开户市
     * @param phone         绑卡手机号
     * @param bankBranchName 支行名称
     * @param cardType      卡类型
     * @param bankName      银行名称
     * @param userName      开户用户名
     * @param abbreviation  银行英文简拼
     * @param userId        userId
     * @param beforeCardNo  修改前的卡号
     * @param cardNo        修改后的卡号
     * @param securityCode  信用卡安全码
     * @param expiredTime   信用卡有效期
     * @return
     */
    @PostMapping(value = "/v1.0/user/freeQtuick/modifyMerchantSettlementInfo/{token}")
    public @ResponseBody Object modifyMerchantSettlementInfo(@PathVariable("token") String token,
                                                             @RequestParam("lineNo") String lineNo,
                                                             @RequestParam("province") String province,
                                                             @RequestParam("city") String city,
                                                             @RequestParam("phone") String phone,
                                                             @RequestParam("bankBranchName") String bankBranchName,
                                                             @RequestParam("cardType") String cardType,
                                                             @RequestParam("bankName") String bankName,
                                                             @RequestParam("userName") String userName,
                                                             @RequestParam("abbreviation") String abbreviation,
                                                             @RequestParam(value = "userId", defaultValue = "0") long userId,
                                                             @RequestParam("beforeCardNo") String beforeCardNo,
                                                             @RequestParam("securityCode") String securityCode,
                                                             @RequestParam("expiredTime") String expiredTime,
                                                             @RequestParam("cardNo") String cardNo) {
        long sysUserId;
        try {
            sysUserId = TokenUtil.getUserId(token);
        } catch (Exception e) {
            return CommonsUtil.returnError("token无效！");
        }

        // 1、根据userId获取当前系统管理员的角色信息
        try {
            long roleId = getUserRoleId(sysUserId);
            if (roleId != 1) {
                // 1为系统管理员
                return CommonsUtil.returnError("非系统管理员无法为该商户修改结算卡信息！");
            }
        } catch (Exception e) {
            e.printStackTrace();
            return CommonsUtil.returnError("获取系统管理员角色信息失败！");
        }

        try {
            if (beforeCardNo.equals(cardNo)) {
                return CommonsUtil.returnError("您无法修改商户结算卡信息，请选择其他结算卡！");
            }
            Map<String, String> map = freeQuickService.modifyMerchantSettlementInfo(lineNo, province, city, phone, bankBranchName, cardType, bankName,
                    userName, abbreviation, userId, beforeCardNo, cardNo, securityCode, expiredTime);
            return CommonsUtil.returnSuccess("", map);
        } catch (ServiceException e) {
            return CommonsUtil.returnError(e.getMessage());
        } catch (Exception e) {
            return CommonsUtil.returnError("服务器异常，请稍后再试！");
        }
    }

    /**
     * 后台-商户查询已绑卡接口：商户通过该接口可以查询已绑定的所有银行卡信息。
     * @param merchantNo 商户号
     * @param channelProductCode：非必传，不传查该商户所有通道成功的绑卡记录，有值查该通道下面的成功绑卡记录。
     * @return
     */
    @GetMapping(value = "/v1.0/user/freeQtuick/queryBankCardList")
    public @ResponseBody Object queryBankCardList(@RequestParam("merchantNo") String merchantNo,
                                                  @RequestParam(value = "channelProductCode", required = false, defaultValue = "") String channelProductCode) {
        try {
            JSONArray jsonArray = freeQuickService.queryBankCardList(merchantNo, channelProductCode);
            return CommonsUtil.returnSuccess("", jsonArray);
        } catch (ServiceException e) {
            e.printStackTrace();
            return CommonsUtil.returnError(e.getMessage());
        } catch (Exception e) {
            e.printStackTrace();
            return CommonsUtil.returnError("服务器异常，请稍后再试！");
        }
    }

    /**
     * 后台-商户提现余额查询接口：商户通过该接口可以从平台查询用户的余额结果，根据余额判断是否进行提现。
     * @param merchantNo 商户号
     * @return
     */
    @GetMapping(value = "/v1.0/user/freeQtuick/queryMerchantWallet")
    public @ResponseBody Object queryMerchantWallet(String merchantNo) {
        if (StringUtils.isEmpty(merchantNo)) {
            return CommonsUtil.returnError("商户号为空！");
        }
        try {
            Map<String, String> map = freeQuickService.queryMerchantWallet(merchantNo);
            return CommonsUtil.returnSuccess("", map);
        } catch (ServiceException e) {
            e.printStackTrace();
            return CommonsUtil.returnError(e.getMessage());
        } catch (Exception e) {
            e.printStackTrace();
            return CommonsUtil.returnError("服务器异常，请稍后再试！");
        }
    }

    /**
     * 商户修改产品费率：代理商通过该接口可修改已开通的产品费率信息
     * @param merchantNo 商户编号
     * @param channelProductCode 通道产品编码
     * @param cardType 卡类型：借记卡-DEBIT，贷记卡-CREDIT
     * @param bizType 费类型：交易-TRADE，提现费率-WITHDRAW_RATE，单笔提现费-WITHDRAW_SIGLE
     * @param feeValue 费率：BigDecimal(10, 4)，精度为小数位后4位；注：当修改提现手续费时精度为小数位后2位，不能大于等于0.05
     * @param capAmount 封顶金额：BigDecimal(10, 2)，封顶金额，精度为小数位后2位,不填默认不修改
     * @return
     */
    @PostMapping(value = "/v1.0/user/freeQtuick/modifyMerchantFeeInfo/{token}")
    public @ResponseBody Object modifyMerchantFeeInfo(@PathVariable String token,
                                                      @RequestParam String merchantNo,
                                                      @RequestParam(required = false) String channelProductCode,
                                                      @RequestParam String cardType,
                                                      @RequestParam String bizType,
                                                      @RequestParam BigDecimal feeValue,
                                                      @RequestParam(required = false) BigDecimal capAmount) {
        long sysUserId;
        try {
            sysUserId = TokenUtil.getUserId(token);
        } catch (Exception e) {
            e.printStackTrace();
            return CommonsUtil.returnError("token无效！");
        }
        // 1、根据userId获取当前系统管理员的角色信息
        try {
            long roleId = getUserRoleId(sysUserId);
            if (roleId != 1) {
                // 1为系统管理员
                return CommonsUtil.returnError("非系统管理员无法为该商户修改费率信息！");
            }
        } catch (Exception e) {
            e.printStackTrace();
            return CommonsUtil.returnError("获取系统管理员角色信息失败！");
        }
        if ("bizType".equals(bizType)) {
            // 交易
            if (feeValue.compareTo(new BigDecimal("0.05")) >= 0) {
                return CommonsUtil.returnError("费率不能大于等于0.05！");
            }
            if (feeValue.compareTo(new BigDecimal("0.00")) <= 0) {
                return CommonsUtil.returnError("费率必须大于0.00！");
            }
        }
        try {
            Map<String, String> resMap = freeQuickService.modifyMerchantFeeInfoo(merchantNo, channelProductCode, CardType.of(cardType).getValue(), PayTypeQu.of(bizType).getValue(), feeValue, capAmount);
            return CommonsUtil.returnSuccess("", resMap);
        } catch (ServiceException e) {
            e.printStackTrace();
            return CommonsUtil.returnError(e.getMessage());
        } catch (Exception e) {
            e.printStackTrace();
            return CommonsUtil.returnError("服务器异常，请稍后再试！");
        }
    }

    /**
     * 查询商户信息
     * @param merchantNo
     * @return
     */
    @GetMapping(value = "/v1.0/user/freeQtuick/getmerchantinfo")
    public @ResponseBody Object getMerchantInfo(String merchantNo, String channelProductCode) {
        try {
            Map<String, Object> map = freeQuickService.getMerchantInfo(merchantNo, channelProductCode);
            return CommonsUtil.returnSuccess("查询成！", map);
        } catch (ServiceException e) {
            e.printStackTrace();
            return CommonsUtil.returnError(e.getMessage());
        } catch (Exception e) {
            e.printStackTrace();
            return CommonsUtil.returnError("服务器异常，请稍后再试！");
        }
    }

    @GetMapping(value = "/v1.0/user/freeQtuick/querymerchantinfo")
    public @ResponseBody Object queryMerchantInfo(String idCard, String channelProductCode) {
        try {
            Map<String, String> map = freeQuickService.queryMerchantInfo(idCard, channelProductCode);
            return CommonsUtil.returnSuccess("查询成功！", map);
        } catch (ServiceException e) {
            e.printStackTrace();
            return CommonsUtil.returnError(e.getMessage());
        } catch (Exception e) {
            e.printStackTrace();
            return CommonsUtil.returnError("服务器异常，请稍后再试！");
        }
    }

    /**
     * 根据开店管家商户编号查询畅捷通道对应的商户编号
     * @param merchantNo
     * @return
     */
    @PostMapping(value = "/v1.0/user/freeQtuick/queryMerchantNo")
    public @ResponseBody Object queryMerchantNo(String merchantNo) {
        try {
            Map<String, String> resMap = freeQuickService.queryMerchantNo(merchantNo);
            return CommonsUtil.returnSuccess("查询成功！", resMap);
        } catch (ServiceException e) {
            e.printStackTrace();
            return CommonsUtil.returnError(e.getMessage());
        } catch (Exception e) {
            e.printStackTrace();
            return CommonsUtil.returnError("服务器异常，请稍后再试！");
        }
    }
    @PostMapping(value = "/v1.0/user/freeQtuick/query/login")
    public @ResponseBody Object queryLogin(String phone) {
        User user = userLoginRegisterBusiness.queryUserByPhone(phone);
        List<PassageWayRegister> result = passageWayRegisterRepository.findByUserId(String.valueOf(user.getId()));
        String merchantNo = "";
        for (PassageWayRegister passageWayRegister : result) {
            merchantNo = passageWayRegister.getMerchantNo();
            break;
        }
        Map<String,String> pram = new HashMap<>();
        pram.put("merchantNo",merchantNo);
        pram.put("userId",String.valueOf(user.getId()));
        return CommonsUtil.returnOK(pram);
    }
}
